﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace CNative.Utilities
{
    public class FileDataHelper
    {
        public const string ManualService = "ManualService.data";
        /// <summary>
        /// 获取Data文件夹下文件数据信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T GetFileData<T>(string fileName)
        {
            string modulePath = Process.GetCurrentProcess().MainModule.FileName.Replace(Process.GetCurrentProcess().MainModule.ModuleName, "");
            var filePath = Path.Combine(modulePath, "data", fileName);
            if (!File.Exists(filePath)) return default(T);
            using (StreamReader sr = new StreamReader(filePath))
            {
                JsonSerializer serializer = new JsonSerializer();
                //serializer.NullValueHandling = NullValueHandling.Ignore;
                //构建Json.net的读取流  
                JsonReader reader = new JsonTextReader(sr);
                //对读取出的Json.net的reader流进行反序列化，并装载到模型中  
                var dt = serializer.Deserialize<T>(reader);
                return dt;
            }
        }

        /// <summary>
        /// 保存到Data文件夹下
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="data"></param>
        public static void SaveFileData(string fileName, object data)
        {
            string modulePath = Process.GetCurrentProcess().MainModule.FileName.Replace(Process.GetCurrentProcess().MainModule.ModuleName, "");
            var filePath = Path.Combine(modulePath, "data");
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);
            filePath = Path.Combine(filePath, fileName);
            using (StreamWriter sw = new StreamWriter(filePath))
            {
                JsonSerializer serializer = new JsonSerializer();
                //serializer.NullValueHandling = NullValueHandling.Ignore;
                //构建Json.net的写入流  
                JsonWriter writer = new JsonTextWriter(sw);
                //把模型数据序列化并写入Json.net的JsonWriter流中  
                serializer.Serialize(writer, data);
                //ser.Serialize(writer, ht);  
                writer.Close();
                sw.Close();
            }
        }

        /// <summary>
        /// 移除文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void RemoveFileData(string fileName)
        {
            string modulePath = Process.GetCurrentProcess().MainModule.FileName.Replace(Process.GetCurrentProcess().MainModule.ModuleName, "");
            var filePath = Path.Combine(modulePath, "data", fileName);
            File.Delete(filePath);
        }

        public static void CreateFile(string filePath, string text,bool isOverride=false, Encoding encoding= null)
        {
            try
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }
                if (isOverride && File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                if (!File.Exists(filePath))
                {
                    CreateDirectory(GetDirectoryFromFilePath(filePath));

                    //Create File
                    FileInfo file = new FileInfo(filePath);
                    using (FileStream stream = file.Create())
                    {
                        using (StreamWriter writer = new StreamWriter(stream, encoding))
                        {
                            writer.Write(text);
                            writer.Flush();
                        }
                    }
                }
                else
                {
                    using (var fs = File.OpenWrite(filePath))
                    {
                        byte[] bytes = encoding.GetBytes(text);
                        //设定书写的开始位置为文件的末尾
                        fs.Position = fs.Length;
                        //将待写入内容追加到文件末尾
                        fs.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void CreateDirectory(string directoryPath)
        {
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
        }
        public static string GetDirectoryFromFilePath(string filePath)
        {
            FileInfo file = new FileInfo(filePath);
            DirectoryInfo directory = file.Directory;
            return directory.FullName;
        }
        public static void OpenDirectory(string directoryPath)
        {
            if (Directory.Exists(directoryPath))
            {
                System.Diagnostics.Process.Start("explorer.exe", directoryPath);
            }
        }
    }
}
